package witchxml;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
 * @version 0.1.1
 * @author Krzysztof 'Bonsai' Justyński
 */
public class voiceover {

	voiceover() {
	}

	/**
	 * The process method reads all XML files from given directory. <br />
	 * 1. Updates XML files by copying attribute "ID" to attribute "Sound". <br />
	 * 2. Returns TXT files with list of all lines included in chosen language
	 * tag (i.e. "langPolish"). Form of this list: <br />
	 * [ID of text line] content of line <br />
	 * [ID of the next line] content of line
	 * 
	 * @throws JDOMException
	 * @throws IOException
	 */
	public void parse(String xmlPath, int lang) throws JDOMException,
			IOException {
		File path = new File(xmlPath);
		File[] f = path.listFiles();
		xmlPath += File.separator;
		this.checkDirs(xmlPath, "XML - updated tags");
		this.checkDirs(xmlPath, "TXT");
		String language = "";
		if (lang == 0) {
			language = "langPolish";
		}
		if (lang == 1) {
			language = "langFinalEnglish_Short";
		}

		StringBuilder extractedText = new StringBuilder();
		ArrayList<Integer> tagArrayList = new ArrayList<Integer>();
		StringBuilder tagString = new StringBuilder();
		SAXBuilder parser = new SAXBuilder();

		for (int i = 0; i < f.length; i++) {
			if (f[i].isFile()) {
				String fileName = f[i].getName().substring(0,
						f[i].getName().lastIndexOf("."));

				Document doc = parser.build(f[i]);
				Element root = doc.getRootElement();
				List branchEntries = root.getChild("Entries").getChildren();
				extractedText.delete(0, extractedText.length());

				for (int k = 0; k < branchEntries.size(); k++) {
					Element entry = (Element) branchEntries.get(k);
					if (entry != null) {
						String id = entry.getAttributeValue("Id");
						if (entry.getAttribute("Sound") != null) {
							entry.setAttribute("Sound", id);
						}
						Element text = entry.getChild("Text");
						if (text != null) {
							Element langPL = text.getChild(language);
							if (langPL != null) {
								extractedText.append("[" + id + "] "
										+ langPL.getTextTrim()
										+ System.getProperty("line.separator"));
							}
							if (langPL != null) {
								tagArrayList.add(Integer.valueOf(id));
							}
						}
					}
				}

				try {
					Format format = Format.getRawFormat().setOmitDeclaration(
							true);
					XMLOutputter out = new XMLOutputter(format);
					FileWriter xmlwriter = new FileWriter(new File(xmlPath
							+ "XML - updated tags/" + fileName + ".xml"));
					out.output(doc, xmlwriter);
					xmlwriter.flush();
					xmlwriter.close();

					BufferedWriter txtwriter = new BufferedWriter(
							new FileWriter(new File(xmlPath + "TXT/" + fileName
									+ ".txt")));
					txtwriter.write(extractedText.toString());
					txtwriter.close();

					System.out.println(fileName + "... OK");
				} catch (Exception e) {
					System.err.println("Error: " + e.getMessage());
				}
			}
		}

		try {
			Collections.sort(tagArrayList);
			if (tagArrayList.size() > 0) {
				for (int i = 0; i < tagArrayList.size(); i++) {
					tagString.append(tagArrayList.get(i)
							+ System.getProperty("line.separator"));
				}
			}
			BufferedWriter tagwriter = new BufferedWriter(new FileWriter(
					new File(xmlPath + "TXT/_Id.txt")));
			tagwriter.write(tagString.toString());
			tagwriter.close();
		} catch (Exception e) {
			System.err.println("Error: " + e.getMessage());
		}
	}

	/**
	 * Checking/creating directories.
	 * 
	 * @param xmlPath
	 * @param dirType
	 */
	private void checkDirs(String xmlPath, String dirType) {
		File directory = new File(xmlPath + dirType);
		if (directory.isDirectory()) {
			File[] files = directory.listFiles();

			for (int i = 0; i < files.length; i++) {
				boolean success = files[i].delete();
				if (!success) {
					System.out.println("Epic fail!");
				}
			}

		} else {
			new File(xmlPath + dirType).mkdir();
		}
	}
}
